<?php

// **************************************************************
// | Name: 星空框架  订单管理
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-10-29 14:15
// **************************************************************
declare(strict_types=1);

namespace app\xingkong\controller\v1;

use app\common\common\BackendController;
use app\common\model\Order as OrderModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\User as UserModel;
use app\common\model\Shipping as ShippingModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\model\Store as StoreModel;
use app\common\model\GoodsCate as GoodsCateModel;
use app\common\model\Goods as GoodsModel;
use app\common\services\OrderServices;
use app\common\services\FinanceServices;
use app\common\services\SendMsg;
use app\common\services\Task;
use think\facade\Db;
use think\facade\View;

/**
 * @xk 订单管理
 */
class Order extends BackendController
{
    // *********************
    // | 普通订单管理
    // **************************
    /**
     * @xk 订单列表
     *
     * @method orderList
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  StoreModel      $storeModel                [description]
     * @param  GoodsCateModel  $goodsCateModel            [description]
     * @param  GoodsModel      $goodsModel                [description]
     * @param  UserModel       $userModel                 [description]
     * @param  GoodsOrderModel $goodsOrderModel           [description]
     * @return [type]          [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function orderList(SubOrderModel $subOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int) $param['page'] : 1;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $user_keywords = isset($param['user_keywords']) ? $param['user_keywords'] : '';
            $l_user_keywords = isset($param['l_user_keywords']) ? $param['l_user_keywords'] : '';
            $pay_type = isset($param['pay_type']) ? $param['pay_type'] : '';
            $status = isset($param['status']) ? $param['status'] : '';
            $refund_status = isset($param['refund_status']) ? $param['refund_status'] : '';
            $befrom = isset($param['befrom']) ? $param['befrom'] : '';
            $shipping_type = isset($param['shipping_type']) ? $param['shipping_type'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
            $pay_time = isset($param['pay_time']) ? $param['pay_time'] : '';
            $receiving_time = isset($param['receiving_time']) ? $param['receiving_time'] : '';
            $condition = [];
            if ($user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['user_name|name|tel|user_sn','like','%'.$user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['so.user_sn','in',$user_sn_arr];
            }
            if ($l_user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['l_user_sn','like','%'.$l_user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['so.user_sn','in',$user_sn_arr];
            }
            if ('' != $keywords) {
                $condition[] = ['so.order_sn|so.sub_order_sn|so.pay_code|so.company_num|so.name|so.tel|so.province|so.city|so.area|so.address', 'like', '%'.$keywords.'%'];
            }
            if ($pay_type != '') {
                $condition[] = ['so.pay_type','in',$pay_type];
            }
            if ($status != '') {
                $condition[] = ['so.status','in',$status];
            } else {
                $condition[] = ['so.status','<>',6];
            }
            if ($refund_status != '') {
                $condition[] = ['so.refund_status','in',$refund_status];
            } else {
                $condition[] = ['so.refund_status','<>',2];
            }
            if ($shipping_type != '') {
                $condition[] = ['so.shipping_type','in',$shipping_type];
            }
            if ($store_id != '') {
                $condition[] = ['so.store_id','in',$store_id];
            }
            if ($befrom != '') {
                $condition[] = ['so.befrom','in',$befrom];
            }
            if ($goods_cate_id > 0) {
                $goods_ids = $goodsModel->where([['goods_cate_id','=',$goods_cate_id]])->column('goods_id');
                $sub_order_sn_arr = $goodsOrderModel->where([['goods_id','in',$goods_ids]])->column('sub_order_sn');
                $condition[] = ['so.sub_order_sn','in',$sub_order_sn_arr];
            }
            if ('' != $pay_time) {
                $search_time_arr = explode('~', $pay_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['so.pay_time', 'between time', $start_time.','.$end_time];
            }
            if ('' != $receiving_time) {
                $receiving_time_arr = explode('~', $receiving_time);
                $start_time = $receiving_time_arr[0];
                $end_time = $receiving_time_arr[1];
                $condition[] = ['so.receiving_time', 'between time', $start_time.','.$end_time];
            }

            $list = $subOrderModel
            ->withTrashed()
            ->alias('so')
            ->leftJoin('user u', 'u.user_sn=so.user_sn')
            ->leftJoin('store s', 's.store_id=so.store_id')
            ->where($condition)
            ->field('so.`sub_order_id`,so.`sub_order_sn`,so.`status` as status_txt,so.`need_pay`,so.`refund_status`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`total_price`,so.`total_freight`,so.`all_price`,so.`address`,so.`create_time`,so.`tel`,so.`pay_price`,so.`is_buy`,so.`pay_time`,so.`pay_code`,so.`receiving_time`,u.`user_sn`,u.`user_name`,s.`store_name`,so.`content`,u.`l_user_sn`,so.`befrom`,so.`order_sn`,so.`pay_status`')
            ->withAttr('status_txt', function ($value, $data) {
                return getStatusTxt1($value, $data['refund_status']);
            })
            ->withAttr('user_name', function ($value, $data) {
                if ($data['content'] != '') {
                    return '<span style="color:red;">'.$value.'</span>';
                } else {
                    return $value;
                }
            })
            ->withAttr('order_sn',function($value,$data){
              return $data['pay_status']==1?$value:'暂无支付信息';
            })
            ->withAttr('refund_status', function ($value, $data) {
                return $value==1 ? '<span style="color:blue;">部分售后</span>' : ($value==2 ? '<span style="color:red;">整单售后</span>' : '<span style="color:green;">无售后</span>');
            })
            ->withAttr('shipping_type', function ($value, $data) {
                return $value==1 ? '快递邮寄' : '预约自提';
            })
            ->withAttr('pay_time', function ($value, $data) {
                return $value ? $value : '暂无付款记录';
            })
            ->withAttr('receiving_time', function ($value, $data) {
                return $value ? $value : '暂无收货记录';
            })
            ->withAttr('is_buy', function ($value, $data) {
                return $value==0 ? '是' : '否';
            })
            ->withAttr('address', function ($value, $data) {
                return $data['province'].$data['city'].$data['area'].$data['address'];
            })
            ->page($page, $limit)
            ->order(['create_time desc','pay_time desc'])
            ->group('so.sub_order_sn')
            ->select()
            ->toArray();
            $result_count = $subOrderModel
                      ->alias('so')
                      ->where($condition)
                      ->group('so.sub_order_sn')
                      ->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $result_count;
            $all_count = $subOrderModel->withTrashed()->alias('so')->where($condition)->count();
            $sub_order_sn_arr = $subOrderModel->withTrashed()->alias('so')->where($condition)->column('sub_order_sn');
            $all_price = $subOrderModel->withTrashed()->alias('so')->where($condition)->where([['pay_type','in','1,2,4']])->sum('all_price');
            $all_shop_price = $subOrderModel->withTrashed()->alias('so')->where($condition)->where([['pay_type','in','3']])->sum('all_price');
            // $all_price = $goodsOrderModel->withTrashed()->alias('so')->where([['sub_order_sn','in',$sub_order_sn_arr],['pay_type','in','1,2']])->sum('sub_total');
            // $all_shop_price = $goodsOrderModel->withTrashed()->alias('so')->where([['sub_order_sn','in',$sub_order_sn_arr],['pay_type','in','3']])->sum('sub_total');
            $all_cost = $subOrderModel->withTrashed()->alias('so')->where($condition)->sum('total_freight');
            $resultData['show_count'] = '订单合计：'.$all_count.'笔;  共收入运费：'.$all_cost.'元,线上支付：'.$all_price.'元，余额支付：'.$all_shop_price.'元';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        // 获取仓库列表
        $store_list = $storeModel
                      ->where([['status','=',1]])
                      ->field('`store_id`,`store_name`')
                      ->select()
                      ->toArray();
        // 获取商品分类
        $goods_cate_list = $goodsCateModel
                          ->where([['status','=',1]])
                          ->field('`goods_cate_id`,`goods_cate_name`')
                          ->select()
                          ->toArray();
        return View::fetch('', ['store_list'=>$store_list,'goods_cate_list'=>$goods_cate_list]);
    }
    /**
     * @xk 导出订单列表
     *
     * @method exportOrder
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  StoreModel      $storeModel                [description]
     * @param  GoodsCateModel  $goodsCateModel            [description]
     * @param  GoodsModel      $goodsModel                [description]
     * @param  UserModel       $userModel                 [description]
     * @param  GoodsOrderModel $goodsOrderModel           [description]
     * @return [type]          [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function exportOrder(SubOrderModel $subOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $limit = 10000;
        $act = isset($param['act']) ? $param['act'] : 'all';

        switch ($act) {
          case 'choose':
            $sub_order_arr = isset($param['sub_order_arr']) ? $param['sub_order_arr'] : '';
            if ($sub_order_arr == '') {
                $code = 200;
                $msg = '请求成功';
                $result_code = 404;
                $result_msg = '请选择需要导出的数据';
                $this->result($code, $msg, $result_code, $result_msg, $resultData);
            }
            $condition = [];
            $condition[] = ['so.sub_order_id','in',$sub_order_arr];
            break;

          default:
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $user_keywords = isset($param['user_keywords']) ? $param['user_keywords'] : '';
            $pay_type = isset($param['pay_type']) ? $param['pay_type'] : '';
            $status = isset($param['status']) ? $param['status'] : '';
            $refund_status = isset($param['refund_status']) ? $param['refund_status'] : '';
            $befrom = isset($param['befrom']) ? $param['befrom'] : '';
            $shipping_type = isset($param['shipping_type']) ? $param['shipping_type'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
            $pay_time = isset($param['pay_time']) ? $param['pay_time'] : '';
            $receiving_time = isset($param['receiving_time']) ? $param['receiving_time'] : '';
            $l_user_keywords = isset($param['l_user_keywords']) ? $param['l_user_keywords'] : '';
            $condition = [];
            if ($user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['user_name|name|tel|user_sn','like','%'.$user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['so.user_sn','in',$user_sn_arr];
            }
            if ('' != $keywords) {
                $condition[] = ['so.order_sn|so.sub_order_sn|so.company_num|so.name|so.tel|so.province|so.city|so.area|so.address', 'like', '%'.$keywords.'%'];
            }
            if ($l_user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['l_user_sn','like','%'.$l_user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['so.user_sn','in',$user_sn_arr];
            }
            if ($pay_type != '') {
                $condition[] = ['so.pay_type','in',$pay_type];
            }
            if ($status != '') {
                $condition[] = ['so.status','in',$status];
            } else {
                $condition[] = ['so.status','<>',6];
            }
            if ($refund_status != '') {
                $condition[] = ['so.refund_status','in',$refund_status];
            } else {
                $condition[] = ['so.refund_status','<>',2];
            }
            if ($shipping_type != '') {
                $condition[] = ['so.shipping_type','in',$shipping_type];
            }
            if ($store_id != '') {
                $condition[] = ['so.store_id','in',$store_id];
            }
            if ($goods_cate_id > 0) {
                $goods_ids = $goodsModel->where([['goods_cate_id','=',$goods_cate_id]])->column('goods_id');
                $sub_order_sn_arr = $goodsOrderModel->withTrashed()->where([['goods_id','in',$goods_ids]])->column('sub_order_sn');
                $condition[] = ['so.sub_order_sn','in',$sub_order_sn_arr];
            }
            if ('' != $pay_time) {
                $search_time_arr = explode('~', $pay_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['so.pay_time', 'between time', $start_time.','.$end_time];
            }
            if ('' != $receiving_time) {
                $receiving_time_arr = explode('~', $receiving_time);
                $start_time = $receiving_time_arr[0];
                $end_time = $receiving_time_arr[1];
                $condition[] = ['so.receiving_time', 'between time', $start_time.','.$end_time];
            }
            break;
        }
        $allCount = $subOrderModel
                      ->withTrashed()
                      ->alias('so')
                      ->where($condition)
                      ->group('so.sub_order_sn')
                      ->count();
        $limit = 10000;
        $pages = ceil($allCount / $limit);
        for ($i = 1; $i <= $pages; ++$i) {
            $data =$subOrderModel
                  ->withTrashed()
                  ->alias('so')
                  ->leftJoin('user u', 'u.user_sn=so.user_sn')
                  ->leftJoin('store s', 's.store_id=so.store_id')
                  ->where($condition)
                  ->field('so.`sub_order_sn`,so.`status` as status_txt,so.`need_pay`,so.`pay_price`,so.`refund_status`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`total_price`,so.`total_freight`,so.`all_price`,so.`address`,so.`create_time`,so.`tel`,so.`pay_price`,so.`is_buy`,so.`pay_time`,so.`delivery_time`,so.`receiving_time`,u.`user_sn`,u.`user_name`,s.`store_name`,so.`pay_type`,so.`content`,u.`l_user_sn`,so.`pay_status`,so.`pay_status` as show_pay_status,so.`befrom`,so.`company_num`')
                  ->withAttr('status_txt', function ($value, $data) {
                      return getStatusTxt($value, $data['refund_status']);
                  })
                  ->withAttr('pay_price', function ($value, $data) {
                      if ($data['pay_status'] == 1) {
                          return $data['need_pay'];
                      } else {
                          return '暂未支付';
                      }
                  })
                  ->withAttr('show_pay_status', function ($value, $data) {
                      return $value==1 ? '支付成功' : '暂未支付';
                  })
                  ->withAttr('pay_type', function ($value, $data) {
                      if ($data['pay_status'] == 1) {
                        return getPayTypeText($value);
                      } else {
                          return '暂未支付';
                      }
                  })
                  ->withAttr('refund_status', function ($value, $data) {
                      return $value==1 ? '部分售后' : ($value==2 ? '整单售后' : '无售后');
                  })
                  ->withAttr('refund_status', function ($value, $data) {
                      return $value==1 ? '部分售后' : ($value==2 ? '整单售后' : '无售后');
                  })
                  ->withAttr('shipping_type', function ($value, $data) {
                      return $value==1 ? '快递邮寄' : '预约自提';
                  })
                  ->withAttr('pay_time', function ($value, $data) {
                      return $value ? $value : '暂无付款记录';
                  })
                  ->withAttr('receiving_time', function ($value, $data) {
                      return $value ? $value : '暂无收货记录';
                  })
                  ->withAttr('delivery_time', function ($value, $data) {
                      return $value ? $value : '暂无收货记录';
                  })
                  ->withAttr('is_buy', function ($value, $data) {
                      return $value==1 ? '否' : '是';
                  })
                  ->withAttr('address', function ($value, $data) {
                      return $data['province'].$data['city'].$data['area'].$data['address'];
                  })
                ->page($i, $limit)
                ->order(['create_time desc','pay_time desc'])
                ->group('so.sub_order_sn')
                ->select()
                ->toArray();
            $order_data = [];
            if ($data) {
                foreach ($data as $key => $value) {
                    $goods_name_arr = $goodsOrderModel->withTrashed()->where([['sub_order_sn','=',$value['sub_order_sn']]])->column('goods_name,spec_value,buy_num,goods_price,status');
                    $goods_arr = [];
                    $status_arr = [];
                    if ($goods_name_arr) {
                        foreach ($goods_name_arr as $k => $val) {
                            $str = $val['goods_name'];
                            if ($val['spec_value'] != '') {
                                $str .= "(".$val['spec_value'].")";
                            }
                            $str .= '*'.$val['buy_num'];
                            // $str .=" ".getGoodsOrderStatus($val['status']);
                            // $str .='*'.$val['goods_price'];
                            $status_arr[] = getGoodsOrderStatus($val['status']);
                            $goods_arr[] = $str;
                        }
                    }
                    $goods_str = implode("\r\n", $goods_arr);
                    $status_str = implode("\r\n", $status_arr);
                    $arrays = [];
                    $arrays[] = $value['sub_order_sn'];
                    $arrays[] = $value['user_name'];
                    $arrays[] = $value['user_sn'];
                    $arrays[] = $value['name'];
                    $arrays[] = $value['tel'];
                    $arrays[] = $value['address'];
                    $arrays[] = $goods_str;
                    $arrays[] = $status_str;
                    $arrays[] = (float)$value['pay_price']; // 支付金额
                    $arrays[] = (float)$value['total_price'];
                    $arrays[] = (float)$value['total_freight'];
                    $arrays[] = $value['status_txt'];
                    $arrays[] = $value['content'];
                    $arrays[] = $value['pay_time'];
                    $arrays[] = $value['shipping_type'];
                    $arrays[] = $value['refund_status'];
                    $arrays[] = $value['befrom'];
                    $arrays[] = $value['is_buy'];
                    $arrays[] = $value['show_pay_status'];
                    $arrays[] = $value['pay_type'];
                    $arrays[] = $value['l_user_sn'];
                    $arrays[] = $value['receiving_time'];
                    $arrays[] = $value['company_num'];
                    $order_data[] = $arrays;
                }
                $title = ['订单编号','会员','会员号','收货人','联系方式','收货地址','商品名','商品状态','支付金额','商品总金额','运费','订单状态','备注','支付时间','配送方式','售后状态','来源','首购状态','支付状态','支付方式','父级会员号','收货时间','发货单号'];
                $width = [10,10,10,10,12,10,50,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,25];
                $path = '/export/subOrder';
                $export_name = '订单表';
                $result = $subOrderModel->export($title, $order_data, $path, $width, $i, $export_name);
                $url_arr[] = $result;
            }
        }
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 待发货订单导出
     * @method  exportWaitShipping
     * @param   SubOrderModel $subOrderModel  [description]
     * @param   StoreModel $storeModel  [description]
     * @param   GoodsCateModel $goodsCateModel  [description]
     * @param   GoodsModel $goodsModel  [description]
     * @param   UserModel $userModel  [description]
     * @param   GoodsOrderModel $goodsOrderModel  [description]
     * @return  [type] [description]
     * @Version V5.0
     * @Time    2021-11-25
     * @City    青岛
     * @Author  xkyinzhe <zhonghuaxinxing@sina.cn>
     */
    public function exportWaitShipping(SubOrderModel $subOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $search_time = isset($param['search_time']) ? $param['search_time'] : '';
        $limit = 10000;
        $condition = [];
        $condition[] = ['go.shipping_type','=',1];
        $condition[] = ['go.status','in','1'];
        if ('' != $search_time) {
            $search_time_arr = explode('~', $search_time);
            $start_time = $search_time_arr[0];
            $end_time = $search_time_arr[1];
            $condition[] = ['go.pay_time', 'between time', $start_time.','.$end_time];
        }
        $allCount = $subOrderModel
                     ->alias('go')
                     ->where($condition)
                     ->group('go.sub_order_sn')
                     ->count();
        if ($allCount <= 0) {
            $code = 200;
            $msg = '请求成功';
            $result_code = 404;
            $result_msg = '暂时没有需要发货的订单';
            $resultData = [];
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        $limit = 10000;
        $pages = ceil($allCount / $limit);
        for ($i = 1; $i <= $pages; ++$i) {
            $data = $subOrderModel
                   ->alias('go')
                   ->where($condition)
                   ->field('go.`sub_order_sn`')
                   ->page($i, $limit)
                   ->order(['go.create_time desc'])
                   ->group('go.sub_order_sn')
                   ->select()
                   ->toArray();
            $order_data = [];
            if ($data) {
                foreach ($data as $key => $value) {
                    $arrays = [];
                    $arrays[] = $value['sub_order_sn'];
                    $arrays[] = '';
                    $order_data[] = $arrays;
                }
                $title = ['订单编号','物流单号'];
                $width = [20,30];
                $path = '/export/shippingTemplate';
                $export_name = '待发货订单表';
                $result = $subOrderModel->export($title, $order_data, $path, $width, $i, $export_name);
                $url_arr[] = $result;
            }
        }
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 代发货订单明细导出
     * @method                                 exportWaitShippingShow
     * @param                                  SubOrderModel $subOrderModel  [description]
     * @param                                  StoreModel $storeModel  [description]
     * @param                                  GoodsCateModel $goodsCateModel  [description]
     * @param                                  GoodsModel $goodsModel  [description]
     * @param                                  UserModel $userModel  [description]
     * @param                                  GoodsOrderModel $goodsOrderModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：青岛
     * @Time：2022-06-08Tfalse10:false29:05+080
     */
    public function exportWaitShippingShow(SubOrderModel $subOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $limit = 10000;
        $condition[] = ['so.status','=',1];
        $condition[] = ['so.refund_status','<>',2];
        $allCount = $subOrderModel
                      ->withTrashed()
                      ->alias('so')
                      ->where($condition)
                      ->count();
        $limit = 10000;
        $pages = ceil($allCount / $limit);
        for ($i = 1; $i <= $pages; ++$i) {
            $data =$subOrderModel
                  ->withTrashed()
                  ->alias('so')
                  ->leftJoin('user u', 'u.user_sn=so.user_sn')
                  ->leftJoin('store s', 's.store_id=so.store_id')
                  ->where($condition)
                  ->field('so.`sub_order_sn`,so.`status` as status_txt,so.`need_pay`,so.`pay_price`,so.`refund_status`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`total_price`,so.`total_freight`,so.`all_price`,so.`address`,so.`create_time`,so.`tel`,so.`pay_price`,so.`is_buy`,so.`pay_time`,so.`delivery_time`,so.`receiving_time`,u.`user_sn`,u.`user_name`,s.`store_name`,so.`pay_type`,so.`content`,u.`l_user_sn`,so.`pay_status`,so.`pay_status` as show_pay_status,so.`befrom`')
                  ->withAttr('status_txt', function ($value, $data) {
                      return getStatusTxt($value, $data['refund_status']);
                  })
                  ->withAttr('pay_price', function ($value, $data) {
                      if ($data['pay_status'] == 1) {
                          return $data['need_pay'];
                      } else {
                          return '暂未支付';
                      }
                  })
                  ->withAttr('show_pay_status', function ($value, $data) {
                      return $value==1 ? '支付成功' : '暂未支付';
                  })
                  ->withAttr('pay_type', function ($value, $data) {
                      if ($data['pay_status'] == 1) {
                         return getPayTypeText($value);
                      } else {
                          return '暂未支付';
                      }
                  })
                  ->withAttr('refund_status', function ($value, $data) {
                      return $value==1 ? '部分售后' : ($value==2 ? '整单售后' : '无售后');
                  })
                  ->withAttr('shipping_type', function ($value, $data) {
                      return $value==1 ? '快递邮寄' : '预约自提';
                  })
                  ->withAttr('pay_time', function ($value, $data) {
                      return $value ? $value : '暂无付款记录';
                  })
                  ->withAttr('is_buy', function ($value, $data) {
                      return $value==1 ? '否' : '是';
                  })
                  ->withAttr('address', function ($value, $data) {
                      return $data['province'].$data['city'].$data['area'].$data['address'];
                  })
                ->page($i, $limit)
                ->order(['create_time desc'])
                ->select()
                ->toArray();
            $order_data = [];
            if ($data) {
                foreach ($data as $key => $value) {
                    $goods_name_arr = $goodsOrderModel->withTrashed()->where([['sub_order_sn','=',$value['sub_order_sn']],['status','in','1.1,5.12,5.22,5.32,5.34']])->column('goods_name,spec_value,buy_num,goods_price,status,sub_total');
                    $goods_arr = [];
                    $all_price = 0.00;
                    if ($goods_name_arr) {
                        foreach ($goods_name_arr as $k => $val) {
                            $str = $val['goods_name'];
                            if ($val['spec_value'] != '') {
                                $str .= "(".$val['spec_value'].")";
                            }
                            $str .= '*'.$val['buy_num'];
                            $str .=" 状态：".getGoodsOrderStatus($val['status']);
                            // $str .='*'.$val['goods_price'];
                            $all_price += $val['sub_total'];
                            $goods_arr[] = $str;
                        }
                    }
                    $goods_str = implode("\r\n", $goods_arr);
                    $arrays = [];
                    $arrays[] = $value['sub_order_sn'];
                    $arrays[] = $value['user_name'];
                    $arrays[] = $value['user_sn'];
                    $arrays[] = $value['name'];
                    $arrays[] = $value['tel'];
                    $arrays[] = $value['address'];
                    $arrays[] = $goods_str;
                    $arrays[] = (float)$all_price;
                    $arrays[] = (float)$value['all_price'];
                    $arrays[] = (float)$value['pay_price']; // 支付金额
                    $arrays[] = (float)$value['total_freight'];
                    $arrays[] = $value['status_txt'];
                    $arrays[] = $value['show_pay_status'];
                    $arrays[] = $value['pay_type'];
                    $arrays[] = $value['shipping_type'];
                    $arrays[] = $value['pay_time'];
                    $arrays[] = $value['befrom'];
                    $arrays[] = $value['is_buy'];
                    $arrays[] = $value['content'];
                    $arrays[] = $value['l_user_sn'];
                    $order_data[] = $arrays;
                }
                // $title = ['订单编号','会员编号','会员昵称','姓名','电话','地址','订单总价','商品总价格','总运费','商品信息','首购状态','订单状态','售后状态','支付时间','发货时间','收货时间','创建时间'];
                $title = ['订单编号','会员','会员号','收货人','联系方式','收货地址','商品名','商品小计','总计','支付金额','运费','订单状态','支付状态','支付方式','配送方式','支付时间','来源','首购状态','备注','父级会员号'];
                $width = [20,20,20,20,20,60,60,15,15,15,15,15,20,20,20,20,20,40,20];
                $path = '/export/waitShippingShow';
                $export_name = '代发货订单明细表';
                $result = $subOrderModel->export($title, $order_data, $path, $width, $i, $export_name);
                $url_arr[] = $result;
            }
        }
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 回传物流数据
     * @method  importWaitShipping
     * @return  [type] [description]
     * @Version V5.0
     * @Time    2021-11-25
     * @City    青岛
     * @Author  xkyinzhe <zhonghuaxinxing@sina.cn>
     */
    public function importWaitShipping()
    {
        return View::fetch();
    }
    /**
     * @xk 执行物流信息回传
     * @method  doImport
     * @param   SubOrderModel $subOrderModel  [description]
     * @param   GoodsOrderModel $goodsOrderModel  [description]
     * @return  [type] [description]
     * @Version V5.0
     * @Time    2021-11-25
     * @City    青岛
     * @Author  xkyinzhe <zhonghuaxinxing@sina.cn>
     */
    public function doImport(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, SendMsg $sendMsg, Task $taskService)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        $param = request()->param();
        $fileurl = isset($param['fileurl']) ? $param['fileurl'] : '';
        try {
            $search_cell = ['A','B'];
            $search_name = ['sub_order_sn','company_num'];
            $shipping_data = $subOrderModel->import('.'.$fileurl, 0, $search_cell, $search_name);
            if (!$shipping_data) {
                throw new \think\Exception("回传信息异常，请检查数据表", 404);
            }
            // $error_arr = [];
            $i=0;
            $j=0;
            foreach ($shipping_data as $key => $value) {
                if ($value['company_num'] == '') {
                    $j++;
                    continue;
                }
                if ($value['sub_order_sn'] == '') {
                    $j++;
                    continue;
                }

                $order_condition = [];
                $order_condition[] = ['sub_order_sn', '=', $value['sub_order_sn']];
                $order_info = $subOrderModel
                          ->withTrashed()
                          ->where($order_condition)
                          ->field('`user_sn`,`name`,`province`,`tel`,`city`,`address`,`area`,`shipping_type`,`status`')
                          ->find();
                if (!$order_info) {
                    $j++;
                    continue;
                }
                // if (2 == $order_info['shipping_type']) {
                //     $j++;
                //     continue;
                // }
                if (1 != $order_info['status']) {
                    $j++;
                    continue;
                }
                // 查看是否存在未处理的售后
                $refund_count = $goodsOrderModel
                              ->withTrashed()
                              ->where($order_condition)
                              ->where([['status','in','5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31,5.33']])
                              ->count();
                if ($refund_count > 0) {
                    $j++;
                    continue;
                }
                $order_data = [];
                $appcode = config('core_config.aliyun_express.appcode');
                $url = 'https://wuliu.market.alicloudapi.com/exCompany?no='.$value['company_num'];
                $headers = [
                  'Authorization:APPCODE '.$appcode
                ];
                $result = https_request($url, [], $headers);
                $data = json_decode($result, true);
                $order_data['company_name'] = '未知';
                if ($data['msg'] == 'ok' && $data['status'] == 0) {
                    $order_data['company_name'] = $data['list'][0]['name']; // 第一个快递公司
                }
                $order_data['company_num'] = $value['company_num'];
                $order_data['sub_order_sn'] = $value['sub_order_sn'];
                $order_data['delivery_time'] = date('Y-m-d H:i:s');
                $order_data['status'] = 2; // 执行订单发货
                $res = $subOrderModel->withTrashed()->where($order_condition)->save($order_data);
                $goods_order_data = [];
                $goods_order_data = $order_data;
                $goods_order_data['order_status'] = 2;
                $goods_order_data['status'] = 2.1;
                $order_condition[] = ['status','in','1.1,5.12,5.22,5.32']; // 产品处于待发货 拒绝各种申请状态
                $order_goods_res = $goodsOrderModel
                                ->withTrashed()
                                ->where($order_condition)
                                ->save($goods_order_data);
                // 执行自动确认收货操作
                $msgData = ['time' => date('YmdHis'), 'msgId' => $value['sub_order_sn'], 'jobAction' => 'orderMakeSure'];
                $delay = config('web_config.shipping_hour')*24*3600;
                $taskService->put($msgData, $delay);
                $i++;
                // 执行发货信息推送
                $create_data = [];
                $create_data['sub_order_sn'] = $value['sub_order_sn'];
                $create_data['company_num'] = $value['company_num'];
                $create_data['company_name'] = $order_data['company_name'];
                $content = '尊敬的用户，您的订单编号为'.$value['sub_order_sn'].'的订单已经交由'.$create_data['company_name'].'公司通过快递单号为：'.$create_data['company_num'].'物流进行运输，请及时关注！';
                $sendMsg->sendPushMsg($order_info['user_sn'], '订单发货通知', $content, 3, $create_data);
            }
            Db::commit();
            $resultData = [];
            $result_code = 200;
            $result_msg = '发货成功';
            unlink('.'.$fileurl);
            $result_msg ='成功'.$i.'条，失败'.$j.'条';
        } catch (\Exception $e) {
            unlink($fileurl);
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 获取订单详情
     *
     * @method orderShow
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  GoodsOrderModel $GoodsOrderModel           [description]
     * @return [type]          [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function orderShow(SubOrderModel $subOrderModel, GoodsOrderModel $GoodsOrderModel, ShippingModel $shippingModel)
    {
        $param = request()->param();
        $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
        $condition = [];
        $condition[] = ['sub_order_sn','=',$sub_order_sn];
        $order_info = $subOrderModel
                  ->withTrashed()
                  ->alias('so')
                  ->leftJoin('store s', 's.store_id=so.store_id')
                  ->leftJoin('user u', 'u.user_sn=so.user_sn')
                  ->where([['so.sub_order_sn', '=', $sub_order_sn]])
                  ->with(['orderGoods'])
                  ->field('so.`sub_order_id`,so.`refund_status`,so.`order_sn`,so.`pay_status`,so.`status`,so.`sub_order_sn`,so.`need_pay`,so.`pay_price`,so.`pay_type`,so.`pay_code`,so.`create_time`,so.`pay_time`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`address`,so.`content`,so.`pay_time`,so.`create_time`,so.`all_price`,so.`total_freight`,so.`need_pay`,s.`store_name`,u.user_name,u.`head_pic`,so.`status` as `status_txt`,so.`delivery_time`,so.`total_price`,so.`cancel_time`,so.`receiving_time`,so.`evaluation_time`,so.`company_num`')
                  ->withAttr('head_pic', function ($value, $data) {
                      return getShowUrl($value);
                  })
                  ->withAttr('status_txt', function ($value, $data) {
                      return getStatusTxt($value, $data['refund_status']);
                  })
                  ->withAttr('pay_status', function ($value, $data) {
                      return 1 == $value ? '支付成功' : '未支付';
                  })
                  ->withAttr('pay_type', function ($value, $data) {
                      return getPayTypeText($value);
                  })
                  ->withAttr('address',function($value,$data){
                    return str_replace("\n","",$value);
                  })
                  ->find();
        $goods_order_count = $GoodsOrderModel->where([['status','=','1.1']])->count();
        return View::fetch('', ['info'=>$order_info ? $order_info->toArray() : [],'sub_order_sn'=>$sub_order_sn,'goods_order_count'=>$goods_order_count]);
    }
    /**
     * @xk 执行订单发货
     *
     * @method getOrderGoods
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  OrderGoodsModel $orderGoodsModel           [description]
     * @return [type]          [description]
     * @Time   2021-09-16
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function getOrderGoods(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, ShippingModel $shippingModel)
    {
        $param = request()->param();
        $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
        $condition = [];
        $condition[] = ['sub_order_sn','=',$sub_order_sn];
        $order_info = $subOrderModel
                ->withTrashed()
                ->alias('so')
                ->leftJoin('store s', 's.store_id=so.store_id')
                ->leftJoin('user u', 'u.user_sn=so.user_sn')
                ->where([['so.sub_order_sn', '=', $sub_order_sn]])
                ->with(['orderGoods'])
                ->field('so.`sub_order_id`,so.`refund_status`,so.`order_sn`,so.`pay_status`,so.`status`,so.`sub_order_sn`,so.`need_pay`,so.`pay_price`,so.`pay_type`,so.`pay_code`,so.`create_time`,so.`pay_time`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`address`,so.`content`,so.`pay_time`,so.`create_time`,so.`all_price`,so.`total_freight`,so.`need_pay`,s.`store_name`,u.user_name,u.`head_pic`,so.`status` as `status_txt`,so.`delivery_time`,so.`total_price`,so.`cancel_time`,so.`receiving_time`,so.`evaluation_time`')
                ->withAttr('head_pic', function ($value, $data) {
                    return getShowUrl($value);
                })
                ->withAttr('status_txt', function ($value, $data) {
                    return getStatusTxt($value);
                })
                ->withAttr('pay_status', function ($value, $data) {
                    return 1 == $value ? '支付成功' : '未支付';
                })
                ->withAttr('pay_type', function ($value, $data) {
                    return getPayTypeText($value);
                })
                ->find();
        // 获取快递公司
        $shipping_list = $shippingModel->where([['status','=',1]])->field('`shipping_id`,`company_code`,`company_name`')->select()->toArray();
        return View::fetch('', ['info'=>$order_info ? $order_info->toArray() : [],'shipping_list'=>$shipping_list,'sub_order_sn'=>$sub_order_sn]);
    }
    /**
     * @xk 执行发货
     *
     * @method doDelivery
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  OrderGoodsModel $orderGoodsModel           [description]
     * @return [type]          [description]
     * @Time   2021-09-16
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function doDelivery(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, Task $taskService, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $company_code = isset($param['company_code']) ? $param['company_code'] : '';
            $company_num = isset($param['company_num']) ? $param['company_num'] : '';
            $company_name = isset($param['company_name']) ? $param['company_name'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $order_goods_id = isset($param['order_goods_id']) ? $param['order_goods_id'] : [];
            if ('' == $sub_order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->withTrashed()->where($condition)->field('`shipping_type`,`user_sn`,`status`,`name`,`tel`,`province`,`city`,`area`,`address`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            // if (2 == $order_info['shipping_type']) {
            //     throw new \think\Exception('当前订单选择自提配送无需发货', 404);
            // }
            if (1 != $order_info['status']) {
                throw new \think\Exception('当前订单状态不允许操作发货', 404);
            }
            if ($company_num == '') {
                throw new \think\Exception("请填写物流单号", 404);
            }
            // 查看是否存在未处理的售后
            $refund_count = $goodsOrderModel->withTrashed()->where($condition)->where([['status','in','5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31']])->count();
            if ($refund_count > 0) {
                throw new \think\Exception("当前订单存在未处理的售后，请先处理完成售后之后在进行发货", 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn','=',$sub_order_sn];
            $order_data = [];
            $appcode = config('core_config.aliyun_express.appcode');
            $url = 'https://wuliu.market.alicloudapi.com/exCompany?no='.$company_num;
            $headers = [
              'Authorization:APPCODE '.$appcode
            ];
            $result = https_request($url, [], $headers);
            $data = json_decode($result, true);
            $order_data['company_name'] = '未知';
            if ($data['msg'] == 'ok' && $data['status'] == 0) {
                $order_data['company_name'] = $data['list'][0]['name'];
            }
            $order_data['company_num'] = $company_num;
            $order_data['status'] = 2;
            $order_data['delivery_time'] = date('Y-m-d H:i:s');
            $res = $subOrderModel->where($condition)->save($order_data);
            $order_goods_data = [];
            $order_goods_data['status'] = 2.1;
            $order_goods_data['order_status'] = 2;
            $order_goods_data['delivery_time'] = date('Y-m-d H:i:s');
            $condition[] = ['order_goods_id','in',$order_goods_id];
            $goodsOrderModel->withTrashed()->where($condition)->save($order_goods_data);
            // xxxx 天之后 自动确认收货
            // 执行退款计划
            $msgData = ['time' => date('YmdHis'), 'msgId' => $sub_order_sn, 'jobAction' => 'orderMakeSure'];
            $delay = config('web_config.shipping_hour')*24*3600;
            $taskService->put($msgData, $delay);
            // 执行发货信息推送
            $create_data = [];
            $create_data['sub_order_sn'] = $sub_order_sn;
            $create_data['company_num'] = $company_num;
            $create_data['company_name'] = $order_data['company_name'];
            $content = '尊敬的用户，您的订单编号为'.$sub_order_sn.'的订单已经交由'.$create_data['company_name'].'公司通过快递单号为：'.$company_num.'物流进行运输，请及时关注！';
            $sendMsg->sendPushMsg($order_info['user_sn'], '订单发货通知', $content, 3, $create_data);
            Db::commit();
            $result_code = 200;
            $result_msg = '发货成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 修改用户地址
     * @method                                      chanageAddress
     * @param                                       SubOrderModel $subOrderModel  [description]
     * @param                                       GoodsOrderModel $goodsOrderModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-25Tfalse16:false17:false45+080
     */
    public function chanageAddress(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $name = isset($param['name']) ? $param['name'] : '';
            $tel = isset($param['tel']) ? $param['tel'] : '';
            $province = isset($param['province']) ? $param['province'] : '';
            $city = isset($param['city']) ? $param['city'] : '';
            $area = isset($param['area']) ? $param['area'] : '';
            $address = isset($param['address']) ? $param['address'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $sub_order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->withTrashed()->where($condition)->field('`sub_order_sn`,`status`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if (2 != $order_info['status'] && $order_info['status'] != 1) {
                throw new \think\Exception('当前订单状态不允许操作发货', 404);
            }
            if ($name == '') {
                throw new \think\Exception("请输入姓名", 404);
            }
            if ($tel == '') {
                throw new \think\Exception("请输入电话", 404);
            }
            if ($province == '') {
                throw new \think\Exception("请输入省市区", 404);
            }
            if ($address == '') {
                throw new \think\Exception("请填写具体地址", 404);
            }

            $condition = [];
            $condition[] = ['sub_order_sn','=',$sub_order_sn];
            $order_data = [];

            $order_data['name'] = $name;
            $order_data['tel'] = $tel;
            $order_data['province'] = $province;
            $order_data['city'] = $city;
            $order_data['area'] = $area;
            $order_data['address'] = $address;
            $res = $subOrderModel->withTrashed()->where($condition)->save($order_data);
            $order_goods_data = [];
            $goodsOrderModel->withTrashed()->where($condition)->save($order_data);
            Db::commit();
            $result_code = 200;
            $result_msg = '地址修改成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 修改物流编号
     * @method          chanageShippingCompany
     * @param           SubOrderModel $subOrderModel  [description]
     * @param           GoodsOrderModel $goodsOrderModel  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-14
     */
    public function chanageShippingCompany(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $company_num = isset($param['company_num']) ? $param['company_num'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $sub_order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->withTrashed()->where($condition)->field('`sub_order_sn`,`status`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if (2 != $order_info['status']) {
                throw new \think\Exception('当前订单不允许执行物流编号修改操作', 404);
            }
            if ($company_num == '') {
                throw new \think\Exception("请输入物流编号", 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn','=',$sub_order_sn];
            $order_data = [];

            $order_data['company_num'] = $company_num;
            $appcode = config('core_config.aliyun_express.appcode');
            $url = 'https://wuliu.market.alicloudapi.com/exCompany?no='.$company_num;
            $headers = [
              'Authorization:APPCODE '.$appcode
            ];
            $result = https_request($url, [], $headers);
            $data = json_decode($result, true);
            $order_data['company_name'] = '未知';
            if ($data['msg'] == 'ok' && $data['status'] == 0) {
                $order_data['company_name'] = $data['list'][0]['name'];
            }
            $res = $subOrderModel->withTrashed()->where($condition)->save($order_data);
            $order_goods_data = [];
            $goodsOrderModel->withTrashed()->where($condition)->save($order_data);

            // 执行发货信息推送
            $create_data = [];
            $create_data['sub_order_sn'] = $sub_order_sn;
            $create_data['company_num'] = $company_num;
            $create_data['company_name'] = $order_data['company_name'];
            $content = '尊敬的用户，您的订单编号为'.$sub_order_sn.'的订单已经交由'.$create_data['company_name'].'公司通过快递单号为：'.$company_num.'物流进行运输，请及时关注！';
            $sendMsg->sendPushMsg($order_info['user_sn'], '订单发货通知', $content, 3, $create_data);

            Db::commit();
            $result_code = 200;
            $result_msg = '物流编号调整成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 添加或修改备注
     * @method          chanageContent
     * @param           SubOrderModel $subOrderModel  [description]
     * @param           GoodsOrderModel $goodsOrderModel  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-14
     */
    public function chanageContent(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $content = isset($param['content']) ? $param['content'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $sub_order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->withTrashed()->where($condition)->field('`sub_order_sn`,`status`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if ($content == '') {
                throw new \think\Exception("请输入备注内容", 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn','=',$sub_order_sn];
            $order_data = [];
            $order_data['content'] = $content;
            $res = $subOrderModel->withTrashed()->where($condition)->save($order_data);
            Db::commit();
            $result_code = 200;
            $result_msg = '备注成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 查询物流
     * @method                                      searchShipping
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-25Tfalse16:false17:false59+080
     */
    public function searchShipping()
    {
        $param = request()->param();
        $company_num = isset($param['company_num']) ? $param['company_num'] : '';
        $tel = isset($param['tel']) ? $param['tel'] : '';
        $appcode = config('core_config.aliyun_express.appcode');
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ('' == $company_num) {
            $result_code = 404;
            $result_msg = '请确认物流单号';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $company_num = $company_num.':'.substr($tel, -4);
        $url = 'https://wuliu.market.alicloudapi.com/kdi?no='.$company_num;
        $headers = [
        'Authorization:APPCODE '.$appcode
      ];
        $result = https_request($url, [], $headers);
        $data = json_decode($result, true);
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        if ($data['msg'] == 'ok' && $data['status'] == 0) {
            foreach ($data['result']['list'] as $key => $value) {
                $show_data = [];
                $show_data['show_date'] =  chanageDateString($value['time'], 7);
                $show_data['show_time'] = chanageDateString($value['time'], 8);
                $show_data['content'] = $value['status'];
                $show_data['time'] = $value['time'];
                $resultData[] = $show_data;
            }
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 自提订单核销
     * @method                                      deSelf
     * @param                                       SubOrderModel $subOrderModel  [description]
     * @param                                       OrderGoodsModel $orderGoodsModel  [description]
     * @param                                       Task $taskService  [description]
     * @param                                       SendMsg $sendMsg  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-24Tfalse16:false35:false21+080
     */
    public function doSelfMakeSure(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, OrderServices $orderServices, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $self_code_no = isset($param['self_code_no']) ? $param['self_code_no'] : '';
            if ('' == $order_sn) {
                throw new \think\Exception('请重新处理需要核销的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $order_sn];
            $order_info = $subOrderModel->withTrashed()->where($condition)->field('`status`,`user_sn`,`self_code_no`,`company_num`,`company_name`,`total_price`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if ($self_code_no == '') {
                throw new \think\Exception("请输入订单核销码", 404);
            }
            if ($self_code_no != $order_info['self_code_no']) {
                throw new \think\Exception("订单核销码和系统记录不一致，请仔细核对", 404);
            }
            if (2 != $order_info['status']) {
                throw new \think\Exception('订单当前不处于可以进行核销的状态', 404);
            }
            // 查看是否存在未处理的售后
            $refund_count = $goodsOrderModel->withTrashed()->where($condition)->where([['status','in','5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31,5.33']])->count();
            if ($refund_count > 0) {
                throw new \think\Exception("当前订单存在未处理的售后，请先处理完成售后之后在进行核销", 404);
            }
            // 执行订单核销
            $res = $subOrderModel
              ->where($condition)
              ->save(['status' => 3, 'receiving_time' => date('Y-m-d H:i:s')]);
            // 修改所有状态正常的商品
            $condition[] = ['status','in','2.1,5.12,5.22,5.32,5.34'];// 所有待收货或待核销商品订单 状态修改为已核销
            $order_goods_res = $goodsOrderModel
                              ->withTrashed()
                              ->where($condition)
                              ->save(['status'=>'3.1','order_status'=>3,'receiving_time'=>date('Y-m-d H:i:s')]);
            $orderServices->syncFinance($order_sn); //  订单收货 或 核销 开始执行业绩结算

            $create_data = [];
            $create_data['sub_order_sn'] = $order_sn;
            $create_data['total_price'] = $order_info['total_price'];
            $create_data['company_name'] = '自提订单';
            $create_data['company_num'] = $self_code_no;
            $content = '尊敬的用户，您的订单编号为'.$order_sn.'的订单已经通过后台核销成功！';
            $sendMsg->sendPushMsg($order_info['user_sn'], '签收通知', $content, 4, $create_data);

            Db::commit();
            $result_code = 200;
            $result_msg = '确认收货成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    // *****************
    // | 售后订单管理
    // **************************
    /**
     * @xk 售后订单列表
     *
     * @method refundOrder
     * @param  RefundOrderModel $refundOrderModel          [description]
     * @param  StoreModel       $storeModel                [description]
     * @param  GoodsCateModel   $goodsCateModel            [description]
     * @param  GoodsModel       $goodsModel                [description]
     * @param  UserModel        $userModel                 [description]
     * @param  GoodsOrderModel  $goodsOrderModel           [description]
     * @return [type]           [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function refundOrder(RefundOrderModel $refundOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel,SubOrderModel $subOrderModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $user_keywords = isset($param['user_keywords']) ? $param['user_keywords'] : '';
            $status = isset($param['status']) ? $param['status'] : '';
            $type = isset($param['type']) ? $param['type'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
            $search_time = isset($param['search_time']) ? $param['search_time'] : '';
            $finish_time = isset($param['finish_time']) ? $param['finish_time'] : '';
            $condition = [];
            if ($user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['user_name|name|tel|user_sn','like','%'.$user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['ref.user_sn','in',$user_sn_arr];
            }
            if ($keywords != '') {
                $sub_order_sn_arr = $goodsOrderModel->where([['sub_order_sn|name|tel|company_num','like','%'.$keywords.'%']])->column('sub_order_sn');
                $condition[] = ['ref.sub_order_sn','in',$sub_order_sn_arr];
            }
            if ($status != '') {
                $condition[] = ['ref.status','in',$status];
            }
            if ($type != '') {
                $condition[] = ['ref.type','in',$type];
            }
            if ($store_id != '') {
                $condition[] = ['ref.store_id','in',$store_id];
            }
            if ('' != $search_time) {
                $search_time_arr = explode('~', $search_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['ref.create_time', 'between time', $start_time.','.$end_time];
            }
            if ('' != $finish_time) {
                $search_time_arr = explode('~', $finish_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['ref.finish_time', 'between time', $start_time.','.$end_time];
            }
            if ($goods_cate_id > 0) {
                $goods_ids = $goodsModel->where([['goods_cate_id','=',$goods_cate_id]])->column('goods_id');
                $sub_order_sn_arr = $goodsOrderModel->where([['goods_id','in',$goods_ids]])->column('sub_order_sn');
                $condition[] = ['ref.sub_order_sn','in',$sub_order_sn_arr];
            }

            $resultData = [];
            if($status != ''){
              $resultData['count'] = $refundOrderModel
                                  ->alias('ref')
                                 ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                                 ->where($condition)
                                 ->group('ref.refund_order_sn')
                                 ->count();
              $resultData['list'] = $refundOrderModel
                                    ->alias('ref')
                                    ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                                    ->leftJoin('user u', 'u.user_sn=ref.user_sn')
                                    ->where($condition)
                                    ->field('ref.*,go.`goods_name`,go.`spec_value`,go.`goods_pic`,go.`goods_price`,go.`buy_num`,u.`user_sn`,u.`user_name`,go.`is_buy`')
                                    ->withAttr('status', function ($value, $data) {
                                      if($data['delete_time']){
                                        return '已取消';
                                      }else{
                                        return getRefundStatusColorText($value);
                                      }
                                    })
                                    ->withAttr('type', function ($value, $data) {
                                      return getRefundTypeTxt($value);
                                    })
                                    ->withAttr('is_buy', function ($value, $data) {
                                        return $value==0 ? '是' : '否';
                                    })
                                    ->page($page, $limit)
                                    ->order(['ref.create_time desc'])
                                    ->group('ref.refund_order_sn')
                                    ->select()
                                    ->toArray();
            }else{
              $resultData['count'] = $refundOrderModel
                                  ->withTrashed()
                                  ->alias('ref')
                                 ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                                 ->where($condition)
                                 ->group('ref.refund_order_sn')
                                 ->count();
              $resultData['list'] = $refundOrderModel
                                ->withTrashed()
                                ->alias('ref')
                                ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                                ->leftJoin('user u', 'u.user_sn=ref.user_sn')
                                ->where($condition)
                                ->field('ref.*,go.`goods_name`,go.`spec_value`,go.`goods_pic`,go.`goods_price`,go.`buy_num`,u.`user_sn`,u.`user_name`,go.`is_buy`')
                                ->withAttr('status', function ($value, $data) {
                                  if($data['delete_time']){
                                    return '已取消';
                                  }else{
                                    return getRefundStatusColorText($value);
                                  }
                                })
                                ->withAttr('type', function ($value, $data) {
                                  return getRefundTypeTxt($value);
                                })
                                ->withAttr('is_buy', function ($value, $data) {
                                    return $value==0 ? '是' : '否';
                                })
                                ->page($page, $limit)
                                ->order(['ref.create_time desc'])
                                ->group('ref.refund_order_sn')
                                ->select()
                                ->toArray();
            }

            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        // 获取仓库列表
        $store_list = $storeModel
                      ->where([['status','=',1]])
                      ->field('`store_id`,`store_name`')
                      ->select()
                      ->toArray();
        // 获取商品分类
        $goods_cate_list = $goodsCateModel
                          ->where([['status','=',1]])
                          ->field('`goods_cate_id`,`goods_cate_name`')
                          ->select()
                          ->toArray();
        return View::fetch('', ['store_list'=>$store_list,'goods_cate_list'=>$goods_cate_list]);
    }
    /**
     * @xk 售后订单数据导出
     *
     * @method exportRefundOrder
     * @param  RefundOrderModel  $refundOrderModel          [description]
     * @param  StoreModel        $storeModel                [description]
     * @param  GoodsCateModel    $goodsCateModel            [description]
     * @param  GoodsModel        $goodsModel                [description]
     * @param  UserModel         $userModel                 [description]
     * @param  GoodsOrderModel   $goodsOrderModel           [description]
     * @return [type]            [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function exportRefundOrder(RefundOrderModel $refundOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel,SubOrderModel $subOrderModel)
    {
        $param = request()->param();
        $limit = 10000;
        $act = isset($param['act']) ? $param['act'] : 'all';
        $keywords = isset($param['keywords']) ? $param['keywords'] : '';
        $user_keywords = isset($param['user_keywords']) ? $param['user_keywords'] : '';
        $status = isset($param['status']) ? $param['status'] : '';
        $type = isset($param['type']) ? $param['type'] : '';
        $store_id = isset($param['store_id']) ? $param['store_id'] : '';
        $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
        $search_time = isset($param['search_time']) ? $param['search_time'] : '';
        $finish_time = isset($param['finish_time']) ? $param['finish_time'] : '';
        $url_arr = [];
        switch ($act) {
          case 'choose':
              $refund_order_ids = isset($param['refund_order_ids']) ? $param['refund_order_ids'] : '';
              $condition = [];
              $condition[] = ['ref.refund_order_id','in',$refund_order_ids];
            break;
          default:
            $condition = [];
            if ($user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['user_name|name|tel|user_sn','like','%'.$user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['ref.user_sn','in',$user_sn_arr];
            }
            if ($keywords != '') {
                $sub_order_sn_arr = $subOrderModel->where([['sub_order_sn|name|tel|company_num','like','%'.$keywords.'%']])->column('sub_order_sn');
                $condition[] = ['ref.sub_order_sn','in',$sub_order_sn_arr];
            }
            if ($status != '') {
                $condition[] = ['ref.status','in',$status];
            }
            if ($type != '') {
                $condition[] = ['ref.type','in',$type];
            }
            if ($store_id != '') {
                $condition[] = ['ref.store_id','in',$store_id];
            }
            if ('' != $search_time) {
                $search_time_arr = explode('~', $search_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['ref.create_time', 'between time', $start_time.','.$end_time];
            }
            if ('' != $finish_time) {
                $search_time_arr = explode('~', $finish_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['ref.finish_time', 'between time', $start_time.','.$end_time];
            }
            if ($goods_cate_id > 0) {
                $goods_ids = $goodsModel->where([['goods_cate_id','=',$goods_cate_id]])->column('goods_id');
                $sub_order_sn_arr = $goodsOrderModel->withTrashed()->where([['goods_id','in',$goods_ids]])->column('sub_order_sn');
                $condition[] = ['ref.sub_order_sn','in',$sub_order_sn_arr];
            }
            break;
        }
        if($status != ''){
          $allCount = $refundOrderModel
                      ->alias('ref')
                      ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                      ->where($condition)
                      ->group('ref.refund_order_sn')
                      ->count();
          $limit = 10000;
          $pages = ceil($allCount / $limit);
          for ($i = 1; $i <= $pages; ++$i) {
              $data = $refundOrderModel
                      ->alias('ref')
                      ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                      ->leftJoin('subOrder so', 'so.sub_order_sn=ref.sub_order_sn')
                      ->leftJoin('user u', 'u.user_sn=ref.user_sn')
                      ->where($condition)
                      ->field('ref.*,go.`goods_name`,go.`spec_value`,go.`goods_pic`,go.`goods_price`,go.`buy_num`,u.`user_sn`,u.`user_name`,go.`name`,go.`tel`,go.`province`,go.`city`,go.`area`,go.`address`,go.`pay_time`,go.`buy_num`,so.`refund_status`')
                      ->withAttr('status', function ($value, $data) {
                        if($data['delete_time']){
                          return '已取消';
                        }else{
                          return getRefundStatusText($value);
                        }
                      })
                      ->withAttr('type', function ($value, $data) {
                          return $value==1 ? '仅退款' : '退货退款';
                      })
                      ->withAttr('address', function ($value, $data) {
                          return $data['province'].' '.$data['city'].' '.$data['area'].' '.$data['address'];
                      })
                      ->order(['ref.create_time desc'])
                      ->page($i, $limit)
                      ->group('ref.refund_order_sn')
                      ->select()
                      ->toArray();
              $order_data = [];
              if ($data) {
                  foreach ($data as $key => $value) {
                      $goods_info = '';
                      $goods_info = $value['goods_name'];
                      if($value['spec_value']){
                        $goods_info .= '('.$value['spec_value'].')';
                      }
                      $goods_info .="*".$value['buy_num'];
                      $arrays = [];
                      $arrays[] = $value['refund_order_sn'];
                      $arrays[] = $value['sub_order_sn'];
                      $arrays[] = $value['user_sn'];
                      $arrays[] = $value['user_name'];
                      $arrays[] = $value['name'];
                      $arrays[] = $value['tel'];
                      $arrays[] = $value['address'];
                      $arrays[] = $goods_info?$goods_info:$value['goods_name'];
                      // $arrays[] = $value['spec_value'];
                      $arrays[] = $value['refund_want_price'];
                      $arrays[] = $value['refund_check_price'];
                      $arrays[] = $value['refund_status']==2?'整单售后':($value['refund_status']==1?'部分售后':'无售后');
                      $arrays[] = $value['type'];
                      $arrays[] = $value['reason'];
                      $arrays[] = $value['status'];
                      $arrays[] = $value['pay_time'];
                      $arrays[] = $value['create_time'];
                      $arrays[] = $value['check_time'];
                      $arrays[] = $value['finish_time'];
                      $order_data[] = $arrays;
                  }
                  $title = ['售后订单编号','关联订单编号','关联会员编号','会员昵称','收货人','联系方式','收货地址','产品名称','申请退款总金额','审核退款金额','是否整单售后','售后类型','售后原因','售后处理状态','支付时间','申请时间','售后处理时间','售后完成时间'];
                  $width = [10,10,10,10,10,12,10,50,10,10,10,10,10,10,20,20,20,20];
                  $path = '/export/subOrder';
                  $export_name = '售后订单表';
                  $result = $refundOrderModel->export($title, $order_data, $path, $width, $i, $export_name);
                  $url_arr[] = $result;
              }
          }
        }else{
          $allCount = $refundOrderModel
                      ->withTrashed()
                      ->alias('ref')
                      ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                      ->where($condition)
                      ->group('ref.refund_order_sn')
                      ->count();
          $limit = 10000;
          $pages = ceil($allCount / $limit);
          for ($i = 1; $i <= $pages; ++$i) {
              $data = $refundOrderModel
                      ->withTrashed()
                    ->alias('ref')
                    ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
                    ->leftJoin('subOrder so', 'so.sub_order_sn=ref.sub_order_sn')
                    ->leftJoin('user u', 'u.user_sn=ref.user_sn')
                    ->where($condition)
                    ->field('ref.*,go.`goods_name`,go.`spec_value`,go.`goods_pic`,go.`goods_price`,go.`buy_num`,u.`user_sn`,u.`user_name`,go.`name`,go.`tel`,go.`province`,go.`city`,go.`area`,go.`address`,go.`pay_time`,go.`buy_num`,so.`refund_status`')
                    ->withAttr('status', function ($value, $data) {
                      if($data['delete_time']){
                        return '已取消';
                      }else{
                        return getRefundStatusText($value);
                      }
                    })
                    ->withAttr('type', function ($value, $data) {
                        return $value==1 ? '仅退款' : '退货退款';
                    })
                    ->withAttr('address', function ($value, $data) {
                        return $data['province'].' '.$data['city'].' '.$data['area'].' '.$data['address'];
                    })
                    ->order(['ref.create_time desc'])
                    ->page($i, $limit)
                    ->group('ref.refund_order_sn')
                    ->select()
                    ->toArray();
              $order_data = [];
              if ($data) {
                  foreach ($data as $key => $value) {
                      $goods_info = '';
                      $goods_info = $value['goods_name'];
                      if($value['spec_value']){
                        $goods_info .= '('.$value['spec_value'].')';
                      }
                      $goods_info .="*".$value['buy_num'];
                      $arrays = [];
                      $arrays[] = $value['refund_order_sn'];
                      $arrays[] = $value['sub_order_sn'];
                      $arrays[] = $value['user_sn'];
                      $arrays[] = $value['user_name'];
                      $arrays[] = $value['name'];
                      $arrays[] = $value['tel'];
                      $arrays[] = $value['address'];
                      $arrays[] = $goods_info?$goods_info:$value['goods_name'];
                      // $arrays[] = $value['spec_value'];
                      $arrays[] = $value['refund_want_price'];
                      $arrays[] = $value['refund_check_price'];
                      $arrays[] = $value['refund_status']==2?'整单售后':($value['refund_status']==1?'部分售后':'无售后');
                      $arrays[] = $value['type'];
                      $arrays[] = $value['reason'];
                      $arrays[] = $value['status'];
                      $arrays[] = $value['pay_time'];
                      $arrays[] = $value['create_time'];
                      $arrays[] = $value['check_time'];
                      $arrays[] = $value['finish_time'];
                      $order_data[] = $arrays;
                  }
                  $title = ['售后订单编号','关联订单编号','关联会员编号','会员昵称','收货人','联系方式','收货地址','产品名称','申请退款总金额','审核退款金额','是否整单售后','售后类型','售后原因','售后处理状态','支付时间','申请时间','售后处理时间','售后完成时间'];
                  $width = [10,10,10,10,10,12,10,50,10,10,10,10,10,10,20,20,20,20];
                  $path = '/export/subOrder';
                  $export_name = '售后订单表';
                  $result = $refundOrderModel->export($title, $order_data, $path, $width, $i, $export_name);
                  $url_arr[] = $result;
              }
          }
        }

        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取售后订单详情
     *
     * @method fefundOrderShow
     * @param  RefundOrderModel $refundOrderModel          [description]
     * @return [type]           [description]
     * @Time   2021-11-02
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function refundOrderShow(RefundOrderModel $refundOrderModel)
    {
        $param = request()->param();
        $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : '';
        $condition = [];
        $condition[] = ['ref.refund_order_sn','=',$refund_order_sn];
        $info = $refundOrderModel
              ->withTrashed()
              ->alias('ref')
              ->leftJoin('goodsOrder go', 'go.goods_order_sn=ref.goods_order_sn')
              ->leftJoin('subOrder sub', 'sub.sub_order_sn=ref.sub_order_sn')
              ->field('ref.*,ref.status as status_txt,ref.type as type_txt,go.`goods_name`,go.`goods_pic`,go.`goods_price`,go.`spec_value`,go.`buy_num`,go.`name`,go.`tel`,go.`province`,go.`city`,go.`area`,go.`address`,go.shipping_type,go.`pay_type`,go.`pay_price`,go.`pay_code`,go.`pay_status`,go.`sub_total` as goods_sub_total,go.`total` as goods_total,go.`freight` as goods_freight,go.`create_time` as show_create_time,go.`pay_time` as show_pay_time,sub.`refund_status` as order_status_show,ref.`return_reason_picarr`,ref.`delete_time`')
              ->where($condition)
              ->withAttr('status_txt', function ($value, $data) {
                  return getRefundStatusText($value);
              })
              ->withAttr('order_status_show', function ($value, $data) {
                  return $value==2 ? '整单售后' : '非整单售后';
              })
              ->withAttr('type_txt', function ($value, $data) {
                  return getRefundTypeTxt($value);
              })
              ->withAttr('pay_status', function ($value, $data) {
                  return 1 == $value ? '支付成功' : '未支付';
              })
              ->withAttr('return_reason_picarr', function ($value, $data) {
                  if ($value) {
                      return getPicArr($value);
                  } else {
                      return '';
                  }
              })
              ->withAttr('pay_type', function ($value, $data) {
                  return getPayTypeText($value);
              })
              ->find();
        return View::fetch('', ['info'=>$info ? $info->toArray() : []]);
    }
    /**
     * @xk 拒绝售后处理
     *
     * @method refuseRefund
     * @param  RefundOrderModel $refundOrderModel          [description]
     * @param  SubOrderModel    $subOrderModel             [description]
     * @param  GoodsOrderModel  $goodsOrderModel           [description]
     * @return [type]           [description]
     * @Time   2021-11-02
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function refuseRefund(RefundOrderModel $refundOrderModel, SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $apply_reason = isset($param['apply_reason']) ? $param['apply_reason'] : '';
            $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : ''; // 售后编号
            $type = isset($param['type']) ? $param['type'] : 1;
            // 查询当前售后信息
            $refund_info = $refundOrderModel
                      ->alias('refund')
                      ->leftJoin('subOrder sub', 'sub.sub_order_sn=refund.sub_order_sn')
                      ->where([['refund_order_sn','=',$refund_order_sn]])
                      ->field('refund.`status`,refund.`order_status`,refund.`sub_order_sn`,refund.`goods_order_sn`,refund.`goods_status`,refund.`type`,sub.`name`,sub.`tel`,sub.`total_price`')
                      ->find();
            if (!$refund_info) {
                throw new \think\Exception("售后订单不存在", 404);
            }
            if ($refund_info['status'] != 0 && !in_array($refund_info['status'],[2.1,2.3,3.1,3.3])) {
                throw new \think\Exception("当前售后订单不在可以进行退款的状态", 404);
            }
            if ($apply_reason == '') {
                throw new \think\Exception("请填写驳回申请的原因", 404);
            }
            $status = 0;
            $goods_status = $refund_info['goods_status']; // 产品状态
            $sub_order_sn = $refund_info['sub_order_sn']; // 产品状态
            $goods_order_sn = $refund_info['goods_order_sn']; // 产品状态
            switch ($type) {
              case '1':
                $status = 1.2;
                $goods_status = 5.12;
                $result_msg = '拒绝退款成功';
                break;
              case '2':
                $status = 2.2;
                $goods_status = 5.22;
                $result_msg = '拒绝退货成功';
                break;
              case '3':
                $status = 3.2;
                $goods_status = 5.32;
                $result_msg = '拒绝换货成功';
                break;
            }
            // 开始写入 售后订单状态
            $refund_res = $refundOrderModel->where([['refund_order_sn','=',$refund_order_sn]])->find()->save(['check_time'=>date('Y-m-d H:i:s'),'status'=>$status,'apply_reason'=>$apply_reason]);
            // 同步订单状态到产品状态
            // 开始写入 售后产品状态
            $goods_order_res = $goodsOrderModel->where([['goods_order_sn','=',$goods_order_sn]])->find()->save(['status'=>$goods_status,'order_status'=>$refund_info['order_status']]);
            // 开始判断当前订单是否还存在未完成的售后  如果不存在
            // 退货/退款订单生成  等待审核
            $order_condition = [];
            $order_condition[] = ['sub_order_sn','=',$sub_order_sn];
            // $order_all = $goodsOrderModel->where($order_condition)->count();//全部订单产品
            $has_order = $goodsOrderModel
                    ->where($order_condition)
                    ->where([['status','in','5.1,5.11,5.13,5.14,5.2,5.21,5.23,5.24,5.25,5.26,5.31,5.33']])
                    ->count();
            $refund_status = 0;
            if ($has_order > 0) {
                $refund_status = 1;
            }
            $order_res = $subOrderModel->where($order_condition)->find()->save(['refund_status'=>$refund_status]);

            $create_data = [];
            $create_data['name'] = $refund_info['name'];
            $create_data['tel'] = $refund_info['tel'];
            $create_data['sub_order_sn'] = $refund_info['sub_order_sn'];
            $create_data['total_price'] = $refund_info['total_price'];
            $create_data['company_name'] = $apply_reason;
            $contentx = '尊敬的用户，您编号为'.$refund_info['sub_order_sn'].'的售后订单订单因为'.$apply_reason.'被后台管理员驳回';
            $sendMsg->sendPushMsg($refund_info['user_sn'], '退款/退货审核结果通知', $contentx, 7, $create_data);


            Db::commit();
            $result_code = 200;
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 同意退货操作
     *
     * @method makeSureReturnRefund
     * @param  RefundOrderModel $refundOrderModel          [description]
     * @param  SubOrderModel    $subOrderModel             [description]
     * @param  GoodsOrderModel  $goodsOrderModel           [description]
     * @return [type]           [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function makeSureReturnRefund(RefundOrderModel $refundOrderModel, SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : ''; // 售后编号
            // 查询当前售后信息
            $refund_info = $refundOrderModel
                      ->where([['refund_order_sn','=',$refund_order_sn]])
                      ->field('`status`,`order_status`,`sub_order_sn`,`goods_order_sn`,`goods_status`,`type`')
                      ->find();
            if (!$refund_info) {
                throw new \think\Exception("售后订单不存在", 404);
            }
            if ($refund_info['status'] != 0) {
                throw new \think\Exception("当前售后订单不在可以进行同意退货的状态", 404);
            }
            $status = 2.1;
            $goods_status = 5.21;
            $goods_order_sn = $refund_info['goods_order_sn'];
            // 开始写入 售后订单状态
            $refund_res = $refundOrderModel
                          ->where([['refund_order_sn','=',$refund_order_sn]])
                          ->find()
                          ->save(['check_time'=>date('Y-m-d H:i:s'),'status'=>$status]);
            // 开始写入 售后产品状态
            $goods_order_res = $goodsOrderModel
                              ->where([['goods_order_sn','=',$goods_order_sn]])
                              ->find()
                              ->save(['status'=>$goods_status]);
            Db::commit();
            $result_code = 200;
            $result_msg = '同意退货成功，请耐心等待买家发货';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 同意换货操作
     * @method                                 makeSureReturnGoods
     * @param                                  RefundOrderModel $refundOrderModel  [description]
     * @param                                  SubOrderModel $subOrderModel  [description]
     * @param                                  GoodsOrderModel $goodsOrderModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：                                  青岛
     * @Time：2022-02-23Tfalse15:false17:07+080
     */
    public function makeSureReturnGoods(RefundOrderModel $refundOrderModel, SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : ''; // 售后编号
            // 查询当前售后信息
            $refund_info = $refundOrderModel
                      ->where([['refund_order_sn','=',$refund_order_sn]])
                      ->field('`status`,`order_status`,`sub_order_sn`,`goods_order_sn`,`goods_status`,`type`')
                      ->find();
            if (!$refund_info) {
                throw new \think\Exception("售后订单不存在", 404);
            }
            if ($refund_info['status'] != 0) {
                throw new \think\Exception("当前售后订单不在可以进行同意退货的状态", 404);
            }
            $status = 3.1;
            $goods_status = 5.31;
            $goods_order_sn = $refund_info['goods_order_sn'];
            // 开始写入 售后订单状态
            $refund_res = $refundOrderModel
                          ->where([['refund_order_sn','=',$refund_order_sn]])
                          ->find()
                          ->save(['check_time'=>date('Y-m-d H:i:s'),'status'=>$status]);
            // 开始写入 售后产品状态
            $goods_order_res = $goodsOrderModel
                              ->where([['goods_order_sn','=',$goods_order_sn]])
                              ->find()
                              ->save(['status'=>$goods_status]);
            Db::commit();
            $result_code = 200;
            $result_msg = '同意换货成功,请等待换货完成';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 执行退款操作
     *
     * @method makeSureRefund
     * @param  RefundOrderModel $refundOrderModel          [description]
     * @param  OrderServices    $orderServices             [description]
     * @return [type]           [description]
     * @Time   2021-11-02
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function makeSureRefundPay(RefundOrderModel $refundOrderModel, GoodsOrderModel $goodsOrderModel, OrderServices $orderServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $refund_check_price = isset($param['refund_check_price']) ? $param['refund_check_price'] : 0;
            $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : ''; // 售后编号
            $type = isset($param['type']) ? $param['type'] : 1;
            // 查询当前售后信息
            $refund_info = $refundOrderModel
                  ->where([['refund_order_sn','=',$refund_order_sn]])
                  ->field('`status`,`order_status`,`sub_order_sn`,`goods_order_sn`,`goods_status`,`type`')
                  ->find();
            if (!$refund_info) {
                throw new \think\Exception("售后订单不存在", 404);
            }
            // if ($refund_info['status'] != 0 && $refund_info['status'] != 2.3) {
            //     throw new \think\Exception("当前售后订单不在可以进行退款的状态", 404);
            // }
            if ($refund_check_price <= 0) {
                throw new \think\Exception("请填写售后退款金额", 404);
            }
            switch ($type) {
              case '1':
                $status = 1.1; // 同意退款
                $goods_status = 5.11;
                break;
              case '2':
                $status = 2.4; // 同意退款
                $goods_status = 5.24;
                break;
            }
            // 开始写入 售后订单状态
            $refund_res = $refundOrderModel
                    ->where([['refund_order_sn','=',$refund_order_sn]])
                    ->find()
                    ->save(['check_time'=>date('Y-m-d H:i:s'),'status'=>$status,'refund_check_price'=>$refund_check_price]);
            // 开始写入 售后产品状态
            $goods_order_res = $goodsOrderModel
                          ->where([['goods_order_sn','=',$refund_info['goods_order_sn']]])
                          ->find()
                          ->save(['status'=>$goods_status]);
            // 执行退款
            $orderServices->syncRefundPay($refund_order_sn);
            Db::commit();
            $result_code = 200;
            $result_msg = '执行操作成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 执行完成换货
     * @method                                      overSureRefundGoods
     * @param                                       RefundOrderModel $refundOrderModel  [description]
     * @param                                       SubOrderModel $subOrderModel  [description]
     * @param                                       GoodsOrderModel $goodsOrderModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-23Tfalse15:false23:false32+080
     */
    public function overSureRefundGoods(RefundOrderModel $refundOrderModel, SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $refund_check_price = isset($param['refund_check_price']) ? $param['refund_check_price'] : 0;
            $refund_order_sn = isset($param['refund_order_sn']) ? $param['refund_order_sn'] : ''; // 售后编号
            $type = isset($param['type']) ? $param['type'] : 3;
            // 查询当前售后信息
            $refund_info = $refundOrderModel
                ->where([['refund_order_sn','=',$refund_order_sn]])
                ->field('`status`,`order_status`,`sub_order_sn`,`goods_order_sn`,`goods_status`,`type`')
                ->find();
            if (!$refund_info) {
                throw new \think\Exception("售后订单不存在", 404);
            }

            $status = 3.4; // 换货完成
            $goods_status = 5.34; // 换货完成
            // 开始写入 售后订单状态
          $refund_res = $refundOrderModel
                  ->where([['refund_order_sn','=',$refund_order_sn]])
                  ->find()
                  ->save(['check_time'=>date('Y-m-d H:i:s'),'finish_time'=>date('Y-m-d H:i:s'),'status'=>$status,'refund_check_price'=>$refund_check_price]);
            // 开始写入 售后产品状态
            $goods_order_res = $goodsOrderModel
                        ->where([['goods_order_sn','=',$refund_info['goods_order_sn']]])
                        ->find()
                        ->save(['status'=>$goods_status,'order_status'=>$refund_info['order_status']]);
            // 开始判断当前订单是否还存在未完成的售后  如果不存在
            // 退货/退款订单生成  等待审核
            $sub_order_sn = $refund_info['sub_order_sn'];
            $order_condition = [];
            $order_condition[] = ['sub_order_sn','=',$sub_order_sn];
            // 换货完成不再属于售后订单
            $has_order = $goodsOrderModel
                                ->where($order_condition)
                                ->where([['status','in','5.1,5.11,5.13,5.14,5.2,5.21,5.23,5.24,5.25,5.26,5.31,5.33']])
                                ->count();
            $refund_status = 0;
            if ($has_order > 0) {
                $refund_status = 1;
            }
            $order_res = $subOrderModel->where($order_condition)->find()->save(['refund_status'=>$refund_status]);
            Db::commit();
            $result_code = 200;
            $result_msg = '执行操作成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 填写回寄物流
     * @method          createCompany
     * @param           RefundOrderModel $refundOrderModel  [description]
     * @param           GoodsOrderModel $goodsOrderModel  [description]
     * @return          [type] [description]
     * @Version：V6.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：青岛
     * @Time：2022-06-30
     */
    public function createCompany(RefundOrderModel $refundOrderModel,GoodsOrderModel $goodsOrderModel){
      Db::startTrans();
      $code = 200;
      $msg = '请求成功';
      $resultData = [];
      try {
          $param = request()->param();
          $refund_order_sn = isset($param['refund_order_sn'])?$param['refund_order_sn']:'';
          $company_num = isset($param['company_num']) ? $param['company_num'] : 0;
          $company_tel = isset($param['company_tel']) ? $param['company_tel'] : ''; // 售后编号
          $status = isset($param['status']) ? $param['status'] : 2.3;
          // 查询当前售后信息
          $refund_info = $refundOrderModel
              ->where([['refund_order_sn','=',$refund_order_sn]])
              ->field('`status`,`order_status`,`sub_order_sn`,`goods_order_sn`,`goods_status`,`type`')
              ->find();
          if (!$refund_info) {
              throw new \think\Exception("售后订单不存在", 404);
          }
          switch ($status) {
            case '2.3':
              $status = 2.3;
              $goods_status = 5.23;
              break;
              case '3.3':
                $status = 3.3;
                $goods_status = 3.23;
                break;
          }
          // 开始写入 售后订单状态
        $refund_res = $refundOrderModel
                ->where([['refund_order_sn','=',$refund_order_sn]])
                ->find()
                ->save(['status'=>$status,'company_num'=>$company_num,'company_tel'=>$company_tel]);
          // 开始写入 售后产品状态
          $goods_order_res = $goodsOrderModel
                      ->where([['goods_order_sn','=',$refund_info['goods_order_sn']]])
                      ->find()
                      ->save(['status'=>$goods_status,'order_status'=>$refund_info['order_status']]);
          Db::commit();
          $result_code = 200;
          $result_msg = '填写回寄物流成功';
      } catch (\Exception $e) {
          Db::rollback();
          $result_code = 404;
          $result_msg = $e->getMessage();
      }
      $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    // ***************
    // | 拣货管理
    // ******************
    /**
     * @xk 拣货管理列表
     *
     * @method picking
     * @param  GoodsOrderModel $goodsOrderModel           [description]
     * @param  StoreModel      $storeModel                [description]
     * @return [type]          [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function picking(GoodsOrderModel $goodsOrderModel, StoreModel $storeModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $pay_time = isset($param['pay_time']) ? $param['pay_time'] : '';
            $status = isset($param['status']) ? $param['status'] : '';
            $goods_status = isset($param['goods_status']) ? $param['goods_status'] : '';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['go.goods_name','like','%'.$keywords.'%'];
            }
            if ($store_id != '') {
                $condition[] = ['go.store_id','in',$store_id];
            }
            if ($goods_status != '') {
                $condition[] = ['go.status','in',$goods_status];
            }
            if ($status != '') {
                $condition[] = ['go.status','in',$status];
            }
            if ('' != $pay_time) {
                $search_time_arr = explode('~', $pay_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                $condition[] = ['go.pay_time', 'between time', $start_time.','.$end_time];
            }
            $resultData = [];
            $goods_list = $goodsOrderModel
                              ->alias('go')
                              ->leftJoin('subOrder so', 'so.sub_order_sn=go.sub_order_sn and so.status=1')
                              ->leftJoin('store s', 's.store_id=go.store_id')
                              ->leftJoin('goods g','g.goods_id = go.goods_id')
                              ->where($condition)
                              ->field('go.`goods_id`,g.`goods_name`,go.`goods_pic`,go.`goods_price`,go.`spec_value`,go.`buy_num`,sum(go.`buy_num`) as all_num,sum(`sub_total`) as all_price,s.`store_name`')
                              ->page($page, $limit)
                              ->group('go.goods_id,go.spec_key')
                              ->select()
                              ->toArray();
            if ($goods_list) {
                foreach ($goods_list as $key => $value) {
                    // 查询当前产品 当前规格 属于首购还是复购
                    $goods_condition = [];
                    $goods_condition[] = ['goods_id','=',$value['goods_id']];
                    $goods_condition[] = ['spec_value','=',$value['spec_value']];
                    if ($goods_status != '') {
                        $goods_condition[] = ['status','in',$goods_status];
                    }
                    if ($status != '') {
                        $goods_condition[] = ['status','in',$status];
                    }
                    if ('' != $pay_time) {
                        $search_time_arr = explode('~', $pay_time);
                        $start_time = $search_time_arr[0];
                        $end_time = $search_time_arr[1];
                        $goods_condition[] = ['pay_time', 'between time', $start_time.','.$end_time];
                    }
                    $goods_list[$key]['first_buy_count'] = $goodsOrderModel
                                                       ->where($goods_condition)
                                                       ->where([['is_buy','=',0]])
                                                       ->sum('buy_num');
                    $goods_list[$key]['next_buy_count'] = $goodsOrderModel
                                                       ->where($goods_condition)
                                                       ->where([['is_buy','=',1]])
                                                       ->sum('buy_num');
                }
            }
            $resultData['list'] = $goods_list;
            $resultData['count'] = $goodsOrderModel->alias('go')->where($condition)->group('goods_id,spec_key')->count();
            $this->result(200, '请求成功', 200, '获取成功', $resultData);
        }
        // 获取仓库列表
        $store_list = $storeModel
                    ->where([['status','=',1]])
                    ->field('`store_id`,`store_name`')
                    ->select()
                    ->toArray();
        $status_list = config('goods_order_status');
        return View::fetch('', ['store_list'=>$store_list,'status_list'=>$status_list]);
    }
    /**
     * @xk 导出拣货统计
     *
     * @method exportPicking
     * @param  GoodsOrderModel $goodsOrderModel           [description]
     * @return [type]          [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function exportPicking(GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $limit = 10000;
        $keywords = isset($param['keywords']) ? $param['keywords'] : '';
        $store_id = isset($param['store_id']) ? $param['store_id'] : '';
        $pay_time = isset($param['pay_time']) ? $param['pay_time'] : '';
        $status = isset($param['status']) ? $param['status'] : '';
        $goods_status = isset($param['goods_status']) ? $param['goods_status'] : '';
        $condition = [];
        if ($keywords != '') {
            $condition[] = ['go.goods_name','like','%'.$keywords.'%'];
        }
        if ($store_id != '') {
            $condition[] = ['go.store_id','in',$store_id];
        }
        if ($goods_status != '') {
            $condition[] = ['go.status','in',$goods_status];
        }
        if ($status != '') {
            $condition[] = ['go.status','in',$status];
        }
        if ('' != $pay_time) {
            $search_time_arr = explode('~', $pay_time);
            $start_time = $search_time_arr[0];
            $end_time = $search_time_arr[1];
            $condition[] = ['go.pay_time', 'between time', $start_time.','.$end_time];
        }

        $allCount = $goodsOrderModel->alias('go')->where($condition)->count();
        $limit = 10000;
        $pages = ceil($allCount / $limit);
        for ($i = 1; $i <= $pages; ++$i) {
            $data = $goodsOrderModel
                  ->alias('go')
                  ->leftJoin('store s', 's.store_id=go.store_id')
                  ->leftJoin('goods g','g.goods_id = go.goods_id')
                  ->where($condition)
                  ->field('go.`goods_id`,g.`goods_name`,go.`goods_pic`,go.`goods_price`,go.`spec_value`,go.`buy_num`,sum(go.`buy_num`) as all_num,sum(`sub_total`) as all_price,s.`store_name`')
                  ->page($i, $limit)
                  ->group('goods_id,spec_key')
                  ->select()
                  ->toArray();
            $order_data = [];
            if ($data) {
                foreach ($data as $key => $value) {
                    // 查询当前产品 当前规格 属于首购还是复购
                    $goods_condition = [];
                    $goods_condition[] = ['goods_id','=',$value['goods_id']];
                    $goods_condition[] = ['spec_value','=',$value['spec_value']];
                    if ($goods_status != '') {
                        $goods_condition[] = ['status','in',$goods_status];
                    }
                    if ($status != '') {
                        $goods_condition[] = ['status','in',$status];
                    }
                    if ('' != $pay_time) {
                        $search_time_arr = explode('~', $pay_time);
                        $start_time = $search_time_arr[0];
                        $end_time = $search_time_arr[1];
                        $goods_condition[] = ['pay_time', 'between time', $start_time.','.$end_time];
                    }
                    $first_buy_count = $goodsOrderModel
                                      ->where($goods_condition)
                                      ->where([['is_buy','=',0]])
                                      ->sum('buy_num');
                    $next_buy_count = $goodsOrderModel
                                      ->where($goods_condition)
                                      ->where([['is_buy','=',1]])
                                      ->sum('buy_num');
                    $arrays = [];
                    $arrays[] = $value['store_name'];
                    $arrays[] = $value['goods_name'];
                    $arrays[] = $value['spec_value'];
                    $arrays[] = $first_buy_count;
                    $arrays[] = $next_buy_count;
                    $arrays[] = $value['all_num'];
                    $arrays[] = $value['all_price'];
                    $order_data[] = $arrays;
                }
                $title = ['所属仓库','产品名称','产品规格','首购数量','复购数量','总计','总金额'];
                $width = [10,30,30,10,10,10];
                $path = '/export/picking';

                $result = $goodsOrderModel->export($title, $order_data, $path, $width, $i, '拣货统计表');
                $url_arr[] = $result;
            }
        }
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 删除订单列表
     * @method          destroyList
     * @param           SubOrderModel $subOrderModel  [description]
     * @param           StoreModel $storeModel  [description]
     * @param           GoodsCateModel $goodsCateModel  [description]
     * @param           GoodsModel $goodsModel  [description]
     * @param           UserModel $userModel  [description]
     * @param           GoodsOrderModel $goodsOrderModel  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-14
     */
    public function destroyList(SubOrderModel $subOrderModel, StoreModel $storeModel, GoodsCateModel $goodsCateModel, GoodsModel $goodsModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int) $param['page'] : 1;
            $limit = isset($param['limit']) ? (int) $param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $user_keywords = isset($param['user_keywords']) ? $param['user_keywords'] : '';

            $befrom = isset($param['befrom']) ? $param['befrom'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
            $pay_time = isset($param['pay_time']) ? $param['pay_time'] : '';
            $condition = [];
            if ($user_keywords != '') {
                $user_condition= [];
                $user_condition[] = ['user_name|name|tel|user_sn|l_user_sn','like','%'.$user_keywords.'%'];
                $user_sn_arr = $userModel->where($user_condition)->column('user_sn');
                $condition[] = ['so.user_sn','in',$user_sn_arr];
            }
            if ('' != $keywords) {
                $condition[] = ['so.order_sn|so.sub_order_sn|so.company_num|so.name|so.tel|so.province|so.city|so.area|so.address', 'like', '%'.$keywords.'%'];
            }
            if ($store_id != '') {
                $condition[] = ['so.store_id','in',$store_id];
            }
            if ($befrom != '') {
                $condition[] = ['so.befrom','in',$befrom];
            }
            if ($goods_cate_id > 0) {
                $goods_ids = $goodsModel->where([['goods_cate_id','=',$goods_cate_id]])->column('goods_id');
                $sub_order_sn_arr = $goodsOrderModel->where([['goods_id','in',$goods_ids]])->column('sub_order_sn');
                $condition[] = ['so.sub_order_sn','in',$sub_order_sn_arr];
            }
            if ('' != $pay_time) {
                $search_time_arr = explode('~', $pay_time);
                $start_time = $search_time_arr[0];
                $end_time = $search_time_arr[1];
                // $start_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[0]).' 00:00:00')); //当前时间0点开始
                // $end_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[1]).' 23:59:59')); //当前时间0点开始
                $condition[] = ['so.delete_time', 'between time', $start_time.','.$end_time];
            }

            $list = $subOrderModel
            ->onlyTrashed()
            ->alias('so')
            ->leftJoin('user u', 'u.user_sn=so.user_sn')
            ->leftJoin('store s', 's.store_id=so.store_id')
            ->where($condition)
            ->field('so.`sub_order_sn`,so.`status` as status_txt,so.`need_pay`,so.`refund_status`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`total_price`,so.`total_freight`,so.`all_price`,so.`address`,so.`create_time`,so.`tel`,so.`pay_price`,so.`is_buy`,so.`pay_time`,so.`receiving_time`,u.`user_sn`,u.`user_name`,s.`store_name`,so.`content`,u.`l_user_sn`,so.`delete_time`')
            ->withAttr('status_txt', function ($value, $data) {
                return getStatusTxt1($value, $data['refund_status']);
            })
            ->withAttr('user_name', function ($value, $data) {
                if ($data['content'] != '') {
                    return '<span style="color:red;">'.$value.'</span>';
                } else {
                    return $value;
                }
            })
            ->withAttr('refund_status', function ($value, $data) {
                return $value==1 ? '<span style="color:blue;">部分售后</span>' : ($value==2 ? '<span style="color:red;">整单售后</span>' : '<span style="color:green;">无售后</span>');
            })
            ->withAttr('shipping_type', function ($value, $data) {
                return $value==1 ? '快递邮寄' : '预约自提';
            })
            ->withAttr('pay_time', function ($value, $data) {
                return $value ? $value : '暂无付款记录';
            })
            ->withAttr('receiving_time', function ($value, $data) {
                return $value ? $value : '暂无收货记录';
            })
            ->withAttr('is_buy', function ($value, $data) {
                return $value==0 ? '是' : '否';
            })
            ->withAttr('address', function ($value, $data) {
                return $data['province'].$data['city'].$data['area'].$data['address'];
            })
            ->page($page, $limit)
            ->order(['create_time desc'])
            ->select()
            ->toArray();
            $result_count = $subOrderModel
                      ->onlyTrashed()
                      ->alias('so')
                      ->where($condition)
                      ->count();
            $code = 200;
            $msg = '请求成功';
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $result_count;
            $all_count = $subOrderModel->onlyTrashed()->alias('so')->where($condition)->count();
            $all_price = $subOrderModel->onlyTrashed()->alias('so')->where($condition)->where([['pay_type','in','1,2,4']])->sum('all_price');
            $all_shop_price = $subOrderModel->onlyTrashed()->alias('so')->where($condition)->where([['pay_type','in','3']])->sum('all_price');
            $all_cost = $subOrderModel->onlyTrashed()->alias('so')->where($condition)->sum('total_freight');
            $resultData['show_count'] = '订单合计：'.$all_count.'笔;  共收入运费：'.$all_cost.',线上支付：'.$all_price.'元，余额支付：'.$all_shop_price.'元';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        // 获取仓库列表
        $store_list = $storeModel
                      ->where([['status','=',1]])
                      ->field('`store_id`,`store_name`')
                      ->select()
                      ->toArray();
        // 获取商品分类
        $goods_cate_list = $goodsCateModel
                          ->where([['status','=',1]])
                          ->field('`goods_cate_id`,`goods_cate_name`')
                          ->select()
                          ->toArray();
        return View::fetch('', ['store_list'=>$store_list,'goods_cate_list'=>$goods_cate_list]);
    }
    /**
     * @xk 删除订单详情
     * @method          destroyorderShow
     * @param           SubOrderModel $subOrderModel  [description]
     * @param           GoodsOrderModel $GoodsOrderModel  [description]
     * @param           ShippingModel $shippingModel  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-14
     */
    public function destroyorderShow(SubOrderModel $subOrderModel, GoodsOrderModel $GoodsOrderModel, ShippingModel $shippingModel)
    {
        $param = request()->param();
        $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
        $condition = [];
        $condition[] = ['sub_order_sn','=',$sub_order_sn];
        $order_info = $subOrderModel
                  ->onlyTrashed()
                  ->alias('so')
                  ->leftJoin('store s', 's.store_id=so.store_id')
                  ->leftJoin('user u', 'u.user_sn=so.user_sn')
                  ->where([['so.sub_order_sn', '=', $sub_order_sn]])
                  ->with(['orderGoods'])
                  ->field('so.`sub_order_id`,so.`refund_status`,so.`order_sn`,so.`pay_status`,so.`status`,so.`sub_order_sn`,so.`need_pay`,so.`pay_price`,so.`pay_type`,so.`pay_code`,so.`create_time`,so.`pay_time`,so.`shipping_type`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`address`,so.`content`,so.`pay_time`,so.`create_time`,so.`all_price`,so.`total_freight`,so.`need_pay`,s.`store_name`,u.user_name,u.`head_pic`,so.`status` as `status_txt`,so.`delivery_time`,so.`total_price`,so.`cancel_time`,so.`receiving_time`,so.`evaluation_time`,so.`company_num`,so.`delete_time`')
                  ->withAttr('head_pic', function ($value, $data) {
                      return getShowUrl($value);
                  })
                  ->withAttr('status_txt', function ($value, $data) {
                      return getStatusTxt($value, $data['refund_status']);
                  })
                  ->withAttr('pay_status', function ($value, $data) {
                      return 1 == $value ? '支付成功' : '未支付';
                  })
                  ->withAttr('pay_type', function ($value, $data) {
                      return getPayTypeText($value);
                  })
                  ->find();
        return View::fetch('', ['info'=>$order_info ? $order_info->toArray() : [],'sub_order_sn'=>$sub_order_sn]);
    }
    /**
     * @xk 月客单价
     * @method          destroyorderShow
     * @param           SubOrderModel $subOrderModel  [description]
     * @param           GoodsOrderModel $GoodsOrderModel  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-14
     */
    public function monthAvgPrice(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        if (request()->isAjax()) {
            $param = request()->param();
            $search_month = isset($param['search_month']) ? $param['search_month'] : data('Y-m');
            if ($search_month == '') {
                $this->result(200, '请求成功', 404, '请选择需要查询的月份');
            }
            $condition = [];
            $condition[] = ['status','=',3.1];
            $condition[] = ['receiving_time','like',$search_month.'%'];
            $all_count = $goodsOrderModel->where($condition)->group('user_sn')->count();
            $all_price = $goodsOrderModel->where($condition)->sum('sub_total');
            $avg_price = 0;
            if ($all_count > 0) {
                $avg_price = sprintf('%.2f', ($all_price/$all_count));
            }
            $this->result(200, '请求成功', 200, '计算成功', ['avg_price'=>$avg_price]);
        }
        return View::fetch();
    }
}
